<template>
    <el-card>
        <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="100px">
            <el-form-item label="机构名称：" prop="deptName">
                <el-input v-model="queryParams.deptName" placeholder="机构名称" size="small"></el-input>
            </el-form-item>
            <el-form-item label="机构全称：" prop="fullName">
                <el-input v-model="queryParams.fullName" placeholder="机构全称" size="small"></el-input>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10">
            <el-col :span="24">
                <div style="margin-bottom: 10px">
                    <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                    <el-button type="danger" plain icon="el-icon-delete" size="small" @click="handleDelete(multipleSelection)">删除</el-button>
                </div>
            </el-col>
        </el-row>
        <el-table :data="tableData" style="width: 100%" row-key="id" border lazy
                :load="load"
                size="small"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                 @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="#" width="50"></el-table-column>
            <el-table-column prop="deptName" label="机构名称"></el-table-column>
            <el-table-column prop="fullName" label="全构名称"></el-table-column>
            <el-table-column prop="deptCategoryName" label="机构类型" width="100"></el-table-column>
            <el-table-column prop="sort" label="排序" width="100"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope"> 
                    <el-button type="text" size="mini" @click="handleView(scope.row)" icon="el-icon-view">查看</el-button>
                    <el-button type="text" size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
                    <el-button size="mini" type="text" @click="handleDelete(scope.row.id)" icon="el-icon-delete">删除</el-button>
                    <el-button size="mini" type="text" @click="handleSubAdd(scope.row)" icon="el-icon-circle-plus-outline">新增子项</el-button>
                </template>
           </el-table-column>
        </el-table>
        <el-dialog :title="formTitle" :visible.sync="deptFormVisible"  @close="resetForm">
        <el-form :model="deptForm" ref="deptForm" :rules="deptRules" :disabled="mode==='view'">
            <el-row :gutter="20">
              <el-col :span="12">
                    <el-form-item prop="deptName"  label="机构名称：" label-width="100px" required>
                        <el-input v-model="deptForm.deptName" autocomplete="off" size="small" placeholder="请输入机构名称"></el-input>
                    </el-form-item>
              </el-col>
               <el-col :span="12">
                   <el-form-item prop="fullName" label="机构全称：" label-width="100px" required>
                     <el-input v-model="deptForm.fullName" autocomplete="off" size="small" placeholder="请输入机构全称"></el-input>
                   </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                    <el-form-item prop="parentId" label="上级机构：" label-width="100px">
                        <el-select v-model="deptForm.parentId" placeholder="请选择所属部门" size="mini" style="width: 100%" :disabled="mode==='addSub'">
                            <el-input
                                placeholder="输入关键字进行过滤"
                                style="padding: 10px;width: 96%"
                                size="mini"
                                v-model="filterText">
                            </el-input>
                            <el-option :value="depetValue" :label="depetLabel" style="height: auto">
                                <el-tree ref="tree" :data="selectDeptTree" highlight-current :filter-node-method="filterNode" @node-click="handleNodeClick"></el-tree>
                            </el-option>
                        </el-select>
                    </el-form-item>
              </el-col>
               <el-col :span="12">
                   <el-form-item prop="deptCategory" label="机构类型：" label-width="100px" required>
                        <el-select v-model="deptForm.deptCategory" placeholder="请选择" size="mini">
                                <el-option
                                v-for="item in deptType"
                                :key="item.dictKey"
                                :label="item.dictValue"
                                :value="item.dictKey">
                                </el-option>
                            </el-select>
                   </el-form-item>
               </el-col>
            </el-row>
             <el-row :gutter="20">
              <el-col :span="12">
                    <el-form-item prop="sort" label="排序：" label-width="100px" required>
                        <el-input-number v-model="deptForm.sort" style="width: 100%" size="mini" controls-position="right" :min="1" :max="10"></el-input-number>
                    </el-form-item>
              </el-col>
               <el-col :span="12">
                   <el-form-item prop="remark" label="备注：" label-width="100px">
                     <el-input v-model="deptForm.remark" autocomplete="off" size="small" placeholder="请输入机构全称"></el-input>
                   </el-form-item>
               </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" v-if="mode!=='view'">
            <el-button type="primary" @click="handleSubmit('deptForm')" size="small">保存</el-button>
            <el-button @click="deptFormVisible = false" size="small">取 消</el-button>
        </div>
      </el-dialog>
    </el-card>
</template>
<script>
import {getDeptList,getDeptSelectTree,getDictionary,save,delDept,getDeptDetail} from '@/api/system/dept.api.js'
    export default {
        data() {
            return {
                  queryParams: {
                      deptName: undefined,
                      fullName: undefined,
                      parentId: undefined
                  },
                 tableData: [],
                 deptFormVisible: false,
                 deptForm: {},
                 formTitle: '新增',
                 selectTreeData: [],
                 filterText: '',
                 depetLabel: '',
                 depetValue: '',
                 selectDeptTree: [],
                 deptType: [],
                 deptRules: {
                    deptName:[
                         { required: true, message: '请输入机构名称', trigger: 'blur' },
                    ],
                    fullName:[
                         { required: true, message: '请输入机构全称', trigger: 'blur' },
                    ],
                     deptCategory:[
                         { required: true, message: '请选择机构类型', trigger: 'blur' },
                    ],
                     sort:[
                         { required: true, message: '请输入机构排序', trigger: 'blur' },
                    ],
                 },
                 multipleSelection: [],
                 mode: 'add'
            }
        },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            },
        },
        methods: {
            // 搜索
            handleQuery() {
                this.queryParams.parentId=undefined
                this.getDeptTableList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getDeptTableList();
            },
              load(tree, treeNode, resolve) {
                const params = {parentId: tree.id}
                getDeptList(params).then(res=>{
                    if(res.code === 200) {
                        resolve(res.data)
                    }
                })
            },
             handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 新增子项
            handleSubAdd(row) {
                this.mode = 'addSub';
                this.deptFormVisible = true;
                this.formTitle = '新增';
                this.depetLabel = row.deptName;
                this.depetValue = row.id;
                this.deptForm.parentId = row.id;
            },
            async handleView(row) {
                await this.getDeptInfo(row.id);
                this.deptFormVisible = true;
                this.formTitle = '查看';
                this.mode = 'view';
            },
            async handleEdit(row) {
                await this.getDeptInfo(row.id);
                this.deptFormVisible = true;
                this.mode = 'edit';
                this.formTitle = '编辑';
            },
             async getDeptInfo(id) {
                 const result = await getDeptDetail(id)
                 if(result.code === 200) {
                    this.deptForm = result.data;
                    this.deptForm.deptCategory = this.deptForm.deptCategory.toString();
                    this.depetLabel = result.data.parentName;
                    this.depetValue = result.data.parentId;
                }
            },
            async handleAdd() {
                this.deptFormVisible = true;
                 const result = await getDeptSelectTree();
                 if(result.code === 200) {
                   this.selectDeptTree = this.getTreeNode(result.data);
                 }
                 this.mode = 'add'
            },
             handleDelete(ids) {
                let deptIds;
                typeof ids === 'string'?deptIds=ids:deptIds=ids.map(item=>item.id).toString();
                this.$confirm('确定将选择的数据删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async () => {
                        const result = await delDept(deptIds);
                        if(result.code === 200) {
                             this.$message({
                                type: 'success',
                                message: '删除成功!'
                           });
                           this.getDeptTableList();
                        }
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },
            handleNodeClick(data) {
                this.deptForm.parentId = data.value;
                this.depetValue = data.value;
                this.depetLabel = data.label;
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            getTreeNode(data) {
                data.forEach(item => {
                    item.label = item.title;
                    if(item.hasChildren) {
                        this.getTreeNode(item.children);
                    }
                });
                return data;
            },
            resetForm() {
               this.$refs['deptForm'].resetFields();
            },
            handleSubmit(formName) {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        let data = {
                            menuId: this.menuId,
                            $deptCategory:  this.deptType.find(item=>{
                                return item.dictKey === this.deptForm.deptCategory
                            }).dictValue,
                            $parentId: this.depetLabel,
                            $tenantId: "",
                            tenantId: "",
                            ...this.deptForm
                        }
                        const result = await save(data);
                        if(result.code === 200) {
                            this.$message({
                                message: '保存成功',
                                type: 'success'
                            });
                            this.deptFormVisible = false;
                            this.getDeptTableList();
                        }
                    } else {
                        return false;
                    }
                });
            },
            async getDeptTableList() {
                const res = await getDeptList(this.queryParams)
                if(res.code === 200) {
                    this.tableData = res.data
                }
            },
        },
         async mounted() {
             this.queryParams.parentId=0;
            this.getDeptTableList();
            const result = await getDeptSelectTree();
            if(result.code === 200) {
              this.selectDeptTree = this.getTreeNode(result.data);
            }
            const result2 = await getDictionary('org_category');
            if(result2.code === 200) {
                this.deptType = this.getTreeNode(result2.data);
            }
        }
       
    }
</script>

<style lang="scss" scoped>

</style>